using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Colorful.Models;
using Colorful.Database;
using System.Reflection;
using Colorful.CMS.Core.Controllers.Admin;
using Colorful.CMS.Core;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Collections.Generic;
using Colorful.CMS;

namespace Colorful.Web.Controllers.Admin
{
    public class CodeController : CMS.Core.Controllers.Admin.CodeController
    {
        protected override void PreSave(Code code, long menuId, bool isNew)
        {
            switch (menuId)
            {
                #region ERP 产品类别
                case (long)MenuEnum.ERP_ProductSort:
                    {
                        using (var db = DbHelper.GetDb())
                        {
                            if (isNew && db.Codes.Any(a => a.MenuId == menuId && a.CodeName == code.CodeName))
                                throw new InvalidException($"代码【{code.CodeName}】已存在！");
                            if (isNew && db.Codes.Any(a => a.MenuId == menuId && a.Name == code.Name))
                                throw new InvalidException($"名称【{code.Name}】已存在！");
                            if (code.Tags == null)
                                code.Tags = new List<string>();
                            if (code.Tags.Count > 0)
                            {
                                foreach (var tag in code.Tags)
                                {
                                    if (!db.Tags.Any(a => a.Name == tag))
                                    {
                                        db.Tags.Add(new Tag()
                                        {
                                            Name = tag,
                                            Sort = (int)menuId,
                                            ByOrder = db.Tags.GetId()
                                        });
                                    }
                                }
                            }
                        }
                    }
                    break;
                    #endregion
            }
        }
    }
}
